package com.orange.zkcase1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: 客户端监听集群节点的动态变化
 */
public class DistributeClient {

    //注意：connectString逗号左右不能有空格，否则连接不上
    private String connectString = "192.168.147.128:2181,192.168.147.129:2181,192.168.147.130:2181";
    //tickTime为2000，initLimit为10
    //LF初次连接时的超时时间应起码大于延迟时间tickTime*initLimit的值否则会因为超时而连接失败。
    private int sessionTimeout = 200000;
    private ZooKeeper zkClient;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DistributeClient client = new DistributeClient();
        //1.获取zk连接
        client.getConnect();

        //2.监听服务器 /servers 下面子节点的增加和删除
        client.getServerList(); //获取servers上的所有节点的上线和下线

        //3.业务逻辑
        client.business();
    }

    private void business() throws InterruptedException {
        //延时阻塞
        Thread.sleep(Long.MAX_VALUE);
    }

    private void getServerList() throws InterruptedException, KeeperException {
        //获取servers下的所有节点信息
        List<String> children = zkClient.getChildren("/servers", true);//对父节点监听

        ArrayList<String> servers = new ArrayList<String>(); //集合用来存所有的服务器节点
        //遍历所有节点  获取节点中的主机名称信息
        for (String child : children) {
            byte[] data = zkClient.getData("/servers/" + child, false, null);
            servers.add(new String(data));
        }
        //打印服务器列表信息
        System.out.println(servers);
    }

    // 创建zookeeper客户端
    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                //收到事件通知后的回调函数（用户的业务逻辑)
                try {
                    //再次启动监听，避免只监听一次
                    getServerList();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
